package codeine.peers_status;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import org.apache.log4j.Logger;

import codeine.configuration.directory.PeerStatusJson;
import codeine.configuration.directory.PeersListJson;
import codeine.executer.Task;

import com.google.common.collect.Maps;

public class OldPeersRemove implements Task{

	private static final Logger log = Logger.getLogger(OldPeersRemove.class);
	public static long INTERVAL = TimeUnit.MINUTES.toMillis(1);
	public static long TIME_TO_LIVE = TimeUnit.DAYS.toMillis(2);
	
	
	@Inject	private PeersListJson peersList;
	@Inject	private PeersListStore PeersListStore;
	
	@Override
	public void run() {
		boolean removed = false;
		Map<String, PeerStatusJson> peers = Maps.newHashMap(peersList.peers());
		for (Iterator<Entry<String, PeerStatusJson>> iterator = peers.entrySet().iterator(); iterator.hasNext();) {
			Entry<String, PeerStatusJson> entry = (Entry<String, PeerStatusJson>) iterator.next();
			if (System.currentTimeMillis() - entry.getValue().update_time() > TIME_TO_LIVE){
				log.info("removing " + entry.getKey());
				iterator.remove();
				removed = true;
			}
		}
		if (removed){
			peersList.updaAll(peers);
			PeersListStore.store();
		}
	}

}
